/**
 * TODO:文件描述
 *
 * @title server.go
 * @projectName grpcDemo
 * @author niuk
 * @date 2024/4/9 8:59
 */

package server

import (
	"context"
	"fmt"
	"grpcDemo/discovery"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"grpcDemo/auth"
	"grpcDemo/calc"
	"net"
)

func init() {
	discovery.AddServiceNode(&discovery.Node{
		Name: "api.grpcdemo.com",
		Addr: "127.0.0.1:8080",
	})
}

func interceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
	authToken, err := auth.GetFromCtx(ctx)
	if err != nil {
		return nil, err
	}
	fmt.Printf("get token ak:%s, sk:%s\n", authToken.Ak, authToken.Sk)
	return handler(ctx, req)
}

func Start(addr string) {
	// 监听端口
	ls, err := net.Listen("tcp", addr)
	if err != nil {
		panic(err)
	}
	defer ls.Close()

	creds, err := credentials.NewServerTLSFromFile("./cert/server.pem", "./cert/server.key")
	if err != nil {
		panic(err)
	}
	// 创建grpc服务
	gServer := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(interceptor))

	// 注册rpc
	calc.RegisterCalcServer(gServer, &calc.Server{})
	if err = gServer.Serve(ls); err != nil {
		panic(err)
	}
}
